package com.yicong.ants.ui.find;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;

import androidx.fragment.app.Fragment;

import com.alibaba.security.realidentity.RPEventListener;
import com.alibaba.security.realidentity.RPResult;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cchao.simplelib.Const;
import com.cchao.simplelib.core.DevHelper;
import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseActivity;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.ui.web.BackAble;
import com.cchao.simplelib.ui.web.WebViewFragment;
import com.cchao.simplelib.util.StringHelper;
import com.cchao.simplelib.util.UrlUtil;
import com.cqyc.imview.TUICallKitUtils;
import com.cqyc.imview.TUIStartUtils;
import com.cqyc.network.Response;
import com.cqyc.network.http.HttpUtil;
import com.cqyc.network.model.GoodsInfo;
import com.cqyc.network.model.ShopInfo;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMValueCallback;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.qcloud.tuikit.tuichat.model.GoodsModel;
import com.tencent.smtt.sdk.WebView;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.x.livesdk.LiveActivity;
import com.yicong.ants.BuildConfig;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.ShareBean;
import com.yicong.ants.databinding.YcWebViewActivityBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.CallBack;
import com.yicong.ants.manager.EnergyHelper;
import com.yicong.ants.manager.RouterHelper;
import com.yicong.ants.manager.RpHelper;
import com.yicong.ants.manager.UiAssistant;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.ad.AntsAdHelper;
import com.yicong.ants.manager.app.AntActivityListener;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.ui.coin.UserCoinActivity;
import com.yicong.ants.ui.main.MainConfigActivity;
import com.yicong.ants.ui.me.PayPwdSettingActivity;
import com.yicong.ants.ui.me.recommend.ShareActivity;
import com.yicong.ants.ui.present.TaskCenterActivity;
import com.yicong.ants.utils.AMapUtil;
import com.yicong.ants.utils.AmapHelper;
import com.yicong.ants.utils.AppUtils;
import com.yicong.ants.utils.FileHelper;
import com.yicong.ants.utils.InitImUtils;
import com.yicong.ants.utils.PermissionsChecker;
import com.yicong.ants.utils.ShareUtils;
import com.yicong.ants.utils.StatusBarUtil;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;

/**
 * webView 线路
 */
public class YcWebViewActivity extends BaseTitleBarActivity<YcWebViewActivityBinding> {
    private static final String CHANNEL_WEIXIN = "CHANNEL_WEIXIN";
    private static final String CHANNEL_ALIPAY = "CHANNEL_ALIPAY";
    WebViewFragment mWebViewFragment;

    @Override
    protected int getLayout() {
        return R.layout.yc_web_view_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleText(getIntent().getStringExtra(Const.Extra.Web_View_Tile));
        setTitleBarVisible(getIntent().getBooleanExtra(Const.Extra.Web_View_Title_Visible, true));
        initTitleShare();
        StatusBarUtil.setWhiteBgDarkText(getWindow());
        mWebViewFragment = (WebViewFragment) this.getSupportFragmentManager().findFragmentById(R.id.fragment);
        initWebView();
        findViewById(R.id.general_title_root).setBackgroundColor(UiHelper.getColor(R.color.white));
        mDataBind.adViewTimer.startTime(mDisposable);
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Login_Suc:
            case Constants.Event.Update_Me_Info:
                mWebViewFragment.onLoadData();
                break;
            case Constants.Event.Ants_Ad_Complete:
                EnergyHelper.doneEnergyTask(thisActivity);
                break;
            case Constants.Event.NO_AD_FINAL:
                UiHelper.showConfirmDialog(this, "您看了太多广告，请更换设备或过一会再试！", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_POSITIVE) {
                        AntActivityListener.exitApp();
                        System.exit(0);
                    }
                });
                break;
        }
    }

    private void initTitleShare() {
        boolean shareAble = getIntent().getBooleanExtra(Constants.Extra.Yc_Web_View_Can_Share, false);
        if (!shareAble) {
            return;
        }
        addTitleMenuItem(UiAssistant.getAtyMenuText(mContext, "分享"), view -> {
            //
            String title = getIntent().getStringExtra(Const.Extra.Web_View_Tile);
            if (StringHelper.isEmpty(title)) {
                title = UiHelper.getString(com.yicong.ants.R.string.app_name);
            }
            BusinessHelper.shareWx(this
                    , title, Constants.Url.Favicon_Image
                    , mWebViewFragment.mCurLoadWebUrl, null);
        });
    }

    private void initWebView() {
        mWebViewFragment.setWebViewHandler(new WebViewFragment.WebViewHandler() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.contains(".com/yc_app/share") || url.contains(".com/app_call_back/share")) {
                    String content = UrlUtil.getValueFromUrl(url, "url");
                    if (StringHelper.isEmpty(content)) {
                        return false;
                    }
                    String title = UrlUtil.getValueFromUrl(url, "title");
                    if (StringHelper.isEmpty(title)) {
                        title = UiHelper.getString(R.string.app_name);
                    }
                    BusinessHelper.shareWx(YcWebViewActivity.this
                            , title, Constants.Url.Favicon_Image,
                            content, null);
                    return true;
                }

                if (url.contains(".com/yc_app/login")) {
                    UserManager.routeLogin(mContext);
                    return true;
                }
                if (url.contains(".com/yc_app/close")) {
                    finish();
                    return true;
                }
                if (url.contains(".com/yc_app/user_center")) {
                    RxBus.get().postEvent(Constants.Event.Expect_Refresh_Dashboard);
                    finish();
                    return true;
                }

                // app 拦截url
                if (url.contains("/api/v2/web/apps")) {
                    switch (UrlUtil.getValueFromUrl(url, "type")) {
                        case "share":
                            // http://api.yctourism.com/api/v2/web/apps?type=share
                            // &title=%E8%9A%81%E4%B8%9B%E7%89%B9%E4%BE%9B%E8%8C%85%E5%8F%B0%E9%95%87%E5%AE%9A%E5%88%B6%E9%85%92%E5%95%86%E5%8A%A1%E5%9E%8B%E3%80%906%E7%93%B6/%E7%AE%B1%E3%80%91
                            // &thumb=http://ant.qiniu.yblylm.com/images/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20201228094327.jpg
                            // &url=http://192.168.0.104:8080/#/goodsdetail?id=46&ants_link=1&utm_souce=utm_mall_app_share&utm_content=10000006
                            String link = UrlUtil.getValueFromUrl(url, "url");
                            if (StringHelper.isEmpty(link)) {
                                return false;
                            }
                            String title = UiHelper.getString(R.string.app_name);
                            String thumb = Constants.Url.Favicon_Image;
                            String shareContent = "";
                            if (StringHelper.isNotEmpty(UrlUtil.getValueFromUrl(url, "title"))) {
                                title = UrlUtil.getValueFromUrl(url, "title");
                            }
                            if (StringHelper.isNotEmpty(UrlUtil.getValueFromUrl(url, "thumb"))) {
                                thumb = UrlUtil.getValueFromUrl(url, "thumb");
                            }
                            if (StringHelper.isNotEmpty(UrlUtil.getValueFromUrl(url, "content"))) {
                                shareContent = UrlUtil.getValueFromUrl(url, "content");
                            }
                            BusinessHelper.shareWx(YcWebViewActivity.this
                                    , title, shareContent, thumb,
                                    link, null);
                            return true;
                        case "login":
                            UserManager.routeLogin(mContext);
                            return true;
                        case "close":
                            finish();
                            return true;
                        case "user_center":
                            RxBus.get().postEvent(Constants.Event.Expect_Refresh_Dashboard);
                            finish();
                            return true;
                        case "pay_wx":
                            payment(url, CHANNEL_WEIXIN);
                            return true;
                        case "pay_ali":
                            payment(url, CHANNEL_ALIPAY);
                            return true;
                        case "rp_check":
                            // 要求人脸认证
                            Map<String, String> map = new HashMap<>();
                            map.put("type", UrlUtil.getValueFromUrl(mWebViewFragment.mInitLoadWebUrl, "extra_type"));
                            map.put("extra_id", UrlUtil.getValueFromUrl(mWebViewFragment.mInitLoadWebUrl, "extra_id"));
                            RpHelper.getRpTokenStart(thisActivity, map, new RPEventListener() {
                                @Override
                                public void onFinish(RPResult auditResult, String code, String msg) {
                                    if (auditResult == RPResult.AUDIT_PASS) {
                                        RpHelper.onRpCheckSuc(thisActivity, () -> {
                                            //
                                            mWebViewFragment.loadJs("rpCheckSuc", null);
                                        });
                                    } else if (auditResult == RPResult.AUDIT_FAIL) {
                                        // 认证不通过。建议接入方调用实人认证服务端接口DescribeVerifyResult来获取最终的认证状态，并以此为准进行业务上的判断和处理。
                                        UiHelper.showConfirmDialog(thisActivity, "认证不通过", null);
                                    } else if (auditResult == RPResult.AUDIT_NOT) {
                                        // 未认证，具体原因可通过code来区分（code取值参见错误码说明），通常是用户主动退出或者姓名身份证号实名校验不匹配等原因，导致未完成认证流程。
                                        UiHelper.showConfirmDialog(thisActivity, "未认证", null);
                                    }
                                }
                            });
                            return true;
                    }
                }
                return false;
            }

            @Override
            public void wrapWebView(WebView view) {
                view.addJavascriptInterface(new NativeBridgeJs(), "AppBridgeJs");
            }
        });
    }

    //支付方式
    private void payment(String url, String type) {
        try {
            String pay_params = UrlUtil.getValueFromUrl(url, "pay_params");
            pay_params = URLDecoder.decode(pay_params);
            JsonObject jsonObject = AppHelper.mParser.parse(pay_params).getAsJsonObject();
            jsonObject.getAsJsonObject("appPayRequest").addProperty("appid", "wxb7aa912b2ee0cf03");
            String appPayRequestStr = JsonHelper.toJson(jsonObject.getAsJsonObject("appPayRequest").toString());
            Logs.d("ycweb::payment " + appPayRequestStr);
            if (type.equals(CHANNEL_WEIXIN)) {
                String appId = getString(R.string.key_wx_app); // 填移动应用(App)的 AppId，非小程序的 AppID
                IWXAPI api = WXAPIFactory.createWXAPI(YcWebViewActivity.this, appId);
                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                req.userName = jsonObject.getAsJsonObject("appPayRequest").get("gh_id").getAsString(); // 填小程序原始id
                req.path = jsonObject.getAsJsonObject("appPayRequest").get("mini_path").getAsString();                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                api.sendReq(req);
            } else if (type.equals(CHANNEL_ALIPAY)) {
                String path = jsonObject.getAsJsonObject("appPayRequest").get("qrCode").getAsString();
                Uri uri = Uri.parse(path);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
//                ZzConfigs.toWebActivity(YcWebViewActivity.this, "支付宝", jsonObject.getAsJsonObject("appPayRequest").get("qrCode").getAsString());
            }
        } catch (Exception e) {
            ToastUtils.showLong("支付失败");
        }
    }

    @Override
    protected void onLoadData() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //如果是文件选择
        if (resultCode == RESULT_OK) {
            //给文件选择的ValueCallback设置onReceiveValue值
            RxBus.get().postEvent(Const.Event.X5_File_Chooser, data.getData());
        } else {
            //给文件选择的ValueCallback设置null值
            RxBus.get().postEvent(Const.Event.X5_File_Chooser, null);
        }
    }

    @Override
    public void onBackPressed() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        for (int i = 0; i < fragments.size(); i++) {
            Fragment fragment = fragments.get(i);
            if (fragment instanceof BackAble) {
                if (((BackAble) fragment).onBackPressed()) {
                    return;
                }
            }
        }
        super.onBackPressed();
    }

    private Dialog requestLocationPermissionDialog;

    public class NativeBridgeJs {
        // 获取经纬度
        @JavascriptInterface
        public void getLocation() {
            if (requestLocationPermissionDialog != null) {
                return;
            }
            runOnUiThread(() -> {
                Logs.logEvent("NativeBridgeJs ", "getLocation");
                if (PermissionsChecker.checkPermissions(YcWebViewActivity.this, Constants.LOCATION2)) {
                    startGetLocation();
                } else {
                    requestLocationPermissionDialog = UiHelper.showConfirmDialog(YcWebViewActivity.this, "权限申请",
                            "需要获取“获取位置”权限，开启后将可以用于获取位置相关的搜索和推荐功能",
                            (dialog, which) -> {
                                switch (which) {
                                    case DialogInterface.BUTTON_POSITIVE:
                                        requestLocationPermissionDialog = null;
                                        addSubscribe(new RxPermissions(YcWebViewActivity.this)
                                                .request(Constants.LOCATION2)
                                                .subscribe(aBoolean -> {
                                                    if (!aBoolean) {
                                                        showToast("没有权限，无法定位所在地");
                                                        return;
                                                    }
                                                    startGetLocation();
                                                }));
                                        break;
                                    case DialogInterface.BUTTON_NEGATIVE:
                                        ToastUtils.showLong("没有权限，无法定位所在地");
                                        requestLocationPermissionDialog = null;
                                        break;
                                }
                            });
                }
            });
        }

        private void startGetLocation() {
            BusinessHelper.checkGps(thisActivity, () -> {
                showProgress();
                // loc
                AmapHelper.startLocation(mContext, aMapLocation -> {
                    hideProgress();
                    Map<String, String> map = new HashMap<>();
                    map.put("city", aMapLocation.getCity());
                    map.put("citycode", aMapLocation.getCityCode());
                    map.put("district", aMapLocation.getDistrict());
                    map.put("street", aMapLocation.getStreet());
                    map.put("adcode", aMapLocation.getAdCode());
                    map.put("province", aMapLocation.getProvince());
                    map.put("address", aMapLocation.getAddress());
                    map.put("latitude", String.valueOf(aMapLocation.getLatitude()));
                    map.put("longitude", String.valueOf(aMapLocation.getLongitude()));
                    Logs.d(" NativeBridgeJs getLocation " + JsonHelper.toJson(map));
                    mWebViewFragment.loadJs("updateLocation", map);

                });
            });
        }

        @JavascriptInterface
        public void activityDegree(String result) {
            JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();
            switch (jsonObject.get("type").getAsString()) {
                case "short_video"://观看热门视频
                    RxBus.get().postEvent(Constants.Event.To_Vide);
                    Router.turnTo(mContext, MainConfigActivity.class).start();
                    EnergyHelper.mEnergyType = "50";
                    AppHelper.mShortVideoTimes = 10;
                    finish();
                    break;
                case "ad_video":  // 观看广告视频
                    if (UserManager.notLogin()) {
                        return;
                    }
                    EnergyHelper.mEnergyType = "30";
                    EnergyHelper.onStartRewardVideo((BaseActivity) mContext);
//                    EnergyHelper.clickEnergyTask((BaseActivity) mContext,AntsAdHelper.Position.energy_task_mall);
                    break;
                case "browse_mall":  // 浏览蚁丛商城
                    EnergyHelper.mEnergyType = "1036";
                    EnergyHelper.energyTaskMall((BaseActivity) mContext);
                    break;
                case "exchange_task":// 任务中心兑换任务
                    ZzConfigs.routeAtyCheckLogin(mContext, TaskCenterActivity.class);
                    break;
                case "new_user":  // 推荐活跃新用户
                    ZzConfigs.routeAtyCheckLogin(mContext, ShareActivity.class);
                    break;
                case "news_browse":  // 新闻
                    Router.turnTo(thisActivity, NewsActivity.class).start();
                    break;
            }
        }

        //打开账户中心
        @JavascriptInterface
        public void jumpGeneralWebPage(String url) {
            RouterHelper.router(thisActivity, url);
        }

        @JavascriptInterface
        public void jumpAccountPage(Object o) {
            ZzConfigs.routeAtyCheckLogin(thisActivity, UserCoinActivity.class);
        }

        @JavascriptInterface
        public void jumpNativePage(String json) {
            try {
                JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
                if ("setPassword".equals(jsonObject.get("pageName").getAsString())) {
                    Router.turnTo(mContext, PayPwdSettingActivity.class).start();
                } else if ("accountCenter".equals(jsonObject.get("pageName").getAsString())) {
                    Router.turnTo(mContext, UserCoinActivity.class).checkLogin(true).start();
                } else if ("tickAccountCenter".equals(jsonObject.get("pageName").getAsString())) {
                    Router.turnTo(mContext, UserCoinActivity.class).putExtra("select", 2).checkLogin(true).start();
                }
            } catch (Throwable ignored) {

            }
        }

        @JavascriptInterface
        public void jumpRoomPage(String json) {
            try {
                JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
                String liveNumber = jsonObject.get("liveNumber").getAsString();
                JsonElement sourceJSON = jsonObject.get("source");
                String source = "";
                if (sourceJSON != null) {
                    source = sourceJSON.getAsString();
                }
                if (!UserManager.isLogin()) {
                    UserManager.routeLogin(YcWebViewActivity.this);
                    return;
                }
                LiveActivity.Companion.start(thisActivity, liveNumber, !"list".equals(source));
            } catch (Throwable ignored) {

            }
        }

        @JavascriptInterface
        public void shareLink(String json) {
            try {
                JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
                String link = jsonObject.get("link").getAsString();
                String title = jsonObject.get("title").getAsString();
                String content = jsonObject.get("content").getAsString();
                String shareImgUrl = jsonObject.get("shareImgUrl").getAsString();
                if ("weChat".equals(jsonObject.get("fromType").getAsString())) {
                    BusinessHelper.shareType(YcWebViewActivity.this, title, content, shareImgUrl, link, SHARE_MEDIA.WEIXIN, null);
                } else if ("antChat".equals(jsonObject.get("fromType").getAsString())) {
                    ShareBean bean = new ShareBean().setTitle(title).setDesc(content).setImage(shareImgUrl).setLink(link);
                    ShareUtils.shareContent(YcWebViewActivity.this, bean);
                }
            } catch (Throwable ignored) {

            }
        }

        @JavascriptInterface
        public void checkAppInstalled(String json) {
            try {
                JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
                JsonArray types = jsonObject.get("types").getAsJsonArray();
                ArrayList<String> result = new ArrayList<>();
                for (Object type : types) {
                    if ("weixin".equals(type)) {
                        result.add(AppUtils.isInstallByread("com.tencent.mm") + "");
                    } else if ("antchat".equals(type)) {
                        result.add(AppUtils.isInstallByread(Constants.YChat_package_name) + "");
                    }
                }
                runOnUiThread(() -> mWebViewFragment.mWebView.loadUrl("javascript:checkAppInstalled(\"" + String.join(",", result) + "\")"));
            } catch (Throwable ignored) {
            }
        }

        @JavascriptInterface
        public void exitWebPage(Object o) {
            finish();
        }

        @JavascriptInterface
        public void saveImage(String o) {
            try {
                JsonObject imageJson = JsonParser.parseString(o).getAsJsonObject();
                String imageStr = imageJson.get("base64").getAsString();
                byte[] decodedString = Base64.decode(imageStr, Base64.DEFAULT);
                Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                FileHelper.saveViewToDirPic(YcWebViewActivity.this, decodedByte);
            } catch (Exception e) {
                ToastUtils.showLong("图片解析失败");
            }
        }


        @JavascriptInterface
        public void goBack(Object o) {
            mDataBind.adViewTimer.post(YcWebViewActivity.this::onBackPressed);
        }


        /***
         * latitude  目标位置的纬度
         * longitude 目标位置的经度
         * currentLatitude  当前位置的纬度
         * currentLongitude  当前位置的经度
         *   addressName  目标位置的名称*/
        @JavascriptInterface
        public void jumpMap(String latitude, String longitude, String currentLatitude, String currentLongitude, String addressName) {
            new Handler(Looper.getMainLooper()).post(() -> {
                AlertDialog dialog = new AlertDialog.Builder(thisActivity).create();
                dialog.setCancelable(true);
                dialog.setCanceledOnTouchOutside(true);
                View view = LayoutInflater.from(thisActivity).inflate(R.layout.dialog_navigation_layout, null);
                view.findViewById(R.id.tv_amap).setOnClickListener(v1 -> {
                    AMapUtil.routeAMap(thisActivity, currentLatitude, currentLongitude, ""
                            , latitude
                            , longitude, addressName);
                    dialog.dismiss();
                });
                view.findViewById(R.id.tv_baidu).setOnClickListener(v12 -> {
                    AMapUtil.routBaiduMap(thisActivity, Double.parseDouble(currentLatitude), Double.parseDouble(currentLongitude), ""
                            , Double.parseDouble(latitude)
                            , Double.parseDouble(longitude), addressName);
                    dialog.dismiss();
                });
                view.findViewById(R.id.tv_cancel).setOnClickListener(v13 -> dialog.dismiss());
                dialog.show();
                Dialogs.requestDialogBottomWidth90(dialog, view);
            });
        }

        //打开单聊
        @JavascriptInterface
        public void openChat(String str) {
            if (TUICallKitUtils.isLogined()) {
                goToChat(str);
            } else {
                if (BuildConfig.Ant_Debug) {
                    ToastUtils.showShort("im启动中...");
                }
                InitImUtils.INSTANCE.log(thisActivity.getApplicationContext(), new TUICallKitUtils.OnImLogCallBack() {
                    @Override
                    public void logCallBack(boolean isSuccess, String msg) {
                        if (isSuccess) {
                            if (BuildConfig.Ant_Debug) {
                                ToastUtils.showShort("im启动完成");
                            }
                            goToChat(str);
                        } else {
                            if (BuildConfig.Ant_Debug) {
                                ToastUtils.showShort("im启动失败" + msg);
                            }
                        }
                    }
                });
            }
        }

        private void goToChat(String str) {
            //店铺id 店铺名称 店铺头像
            Log.e("openChat", "----" + str + "  --  ");
            //{"goodID":160589,"userID":10000003,"merchantName":"烟雨朦胧"}
            new Handler(Looper.getMainLooper()).post(() -> {
                if (!TUICallKitUtils.isLogined()) {
                    ToastUtils.showLong("im尚未启动请稍后重试");
                    return;
                }
                if (str == null || "".equals(str)) {
                    ToastUtils.showLong("数据异常");
                    return;
                }
                JsonElement element = GsonUtils.fromJson(str, JsonElement.class);
                String userID = element.getAsJsonObject().get("userID").getAsString();
                if (element.getAsJsonObject().has("goodID")) {
                    String goodID = element.getAsJsonObject().get("goodID").getAsString();
                    String merchantName = element.getAsJsonObject().get("merchantName").getAsString();
                    HttpUtil.api.findGoods(goodID).enqueue(new Callback<Response<GoodsInfo>>() {
                        @Override
                        public void onResponse(Call<Response<GoodsInfo>> call, retrofit2.Response<Response<GoodsInfo>> response) {
                            if (response.isSuccessful()) {
                                if (response.body() != null && response.body().getData() != null) {
                                    GoodsInfo info = response.body().getData();
                                    GoodsModel goodsModel = new GoodsModel();
                                    goodsModel.item_img = info.getItemImg();
                                    goodsModel.item_name = info.getItemName();
                                    goodsModel.sales_price = info.getSalesPrice();
                                    goodsModel.web_url = info.getWebUrl();
                                    goodsModel.itemStatus = info.getItemStatus();
                                    TUIStartUtils.Companion.startC2CChatActivity(userID, merchantName, "", goodsModel);
                                } else {
                                    ToastUtils.showLong("获取商品信息异常！");
                                }
                            } else {
                                ToastUtils.showLong("获取商品信息异常！");
                            }
                        }

                        @Override
                        public void onFailure(Call<Response<GoodsInfo>> call, Throwable t) {
                            ToastUtils.showLong("获取商品信息异常！");
                        }
                    });
                } else {
                    HttpUtil.api.findMchInfo(userID).enqueue(new Callback<Response<ShopInfo>>() {
                        @Override
                        public void onResponse(Call<Response<ShopInfo>> call, retrofit2.Response<Response<ShopInfo>> response) {
                            if (response.isSuccessful()) {
                                if (response.body() != null && response.body().getData() != null) {
                                    ShopInfo info = response.body().getData();
                                    TUIStartUtils.Companion.startC2CChatActivity(userID, info.getMchName(), info.getMchImg(), null);
                                } else {
                                    ToastUtils.showLong("获取店铺异常！");
                                }
                            } else {
                                ToastUtils.showLong("获取店铺异常！");
                            }
                        }

                        @Override
                        public void onFailure(Call<Response<ShopInfo>> call, Throwable t) {
                            ToastUtils.showLong("获取店铺异常！");
                        }
                    });
                }
            });

        }

        //打开会话列表
        @JavascriptInterface
        public void openConversationList(Object o) {
            new Handler(Looper.getMainLooper()).post(() -> {
                        if (!TUICallKitUtils.isLogined()) {
                            ToastUtils.showLong("im尚未启动请稍后重试");
                            return;
                        }
                        TUIStartUtils.Companion.startConversation();
                    }
            );
        }

        //获取未读消息数
        @JavascriptInterface
        public void getUnReadMsgNumber(Object obj) {
            new Handler(Looper.getMainLooper()).post(() -> {
                if (TUICallKitUtils.isLogined()) {
                    V2TIMManager.getConversationManager().getTotalUnreadMessageCount(new V2TIMValueCallback<Long>() {
                        @Override
                        public void onSuccess(Long aLong) {
                            Log.e("getUnReadMsgNumber", "---" + aLong);
                            putUnReadMsgNumber(mWebViewFragment.mWebView, aLong);
                        }

                        @Override
                        public void onError(int i, String s) {
                            ToastUtils.showLong("获取未读消息失败" + s);
                        }
                    });
                } else {
                    if (BuildConfig.Ant_Debug) {
                        ToastUtils.showShort("im启动中...");
                    }
                    InitImUtils.INSTANCE.log(thisActivity.getApplicationContext(), new TUICallKitUtils.OnImLogCallBack() {
                        @Override
                        public void logCallBack(boolean isSuccess, String msg) {
                            if (isSuccess) {
                                if (BuildConfig.Ant_Debug) {
                                    ToastUtils.showShort("im启动完成");
                                }
                                V2TIMManager.getConversationManager().getTotalUnreadMessageCount(new V2TIMValueCallback<Long>() {
                                    @Override
                                    public void onSuccess(Long aLong) {
                                        Log.e("getUnReadMsgNumber", "---" + aLong);
                                        putUnReadMsgNumber(mWebViewFragment.mWebView, aLong);
                                    }

                                    @Override
                                    public void onError(int i, String s) {
                                        ToastUtils.showLong("获取未读消息失败" + s);
                                    }
                                });
                            } else {
                                if (BuildConfig.Ant_Debug) {
                                    ToastUtils.showShort("im启动失败" + msg);
                                }
                            }
                        }
                    });
                }
            });
        }

        private void putUnReadMsgNumber(WebView webView, long number) {
            webView.loadUrl("javascript:getUnReadMsgNumber(" + number + ")");
        }

        //人脸认证
        @JavascriptInterface
        public void faceAuth(Object object) {
            new Handler(Looper.getMainLooper()).post(() -> {
                RpHelper.startVerify(thisActivity, new CallBack() {
                    @Override
                    public void callBack(String string) {
                        mWebViewFragment.loadJs("rpCheckSuc", null);
                    }
                });
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AntsAdHelper.clearAdInfo(AntsAdHelper.Position.All);
    }
}
